<template>
  <div class="device-info-page">
    <div class="device-info-container">
      <div class="header" style="display:none">
        <van-icon name="arrow-left" class="back-icon" @click="goBack" />
        <h1>在线打酒</h1>
      </div>
      
      <!-- 加载中状态 -->
      <van-loading v-if="loading" type="spinner" color="#1989fa" class="loading" />
      
      <!-- 设备信息内容 -->
      <div v-else class="content">
        <!-- 设备状态 -->
        <div class="device-status-card" v-if="showDeviceStatus">
          <div class="status-header">
            <h2>设备 #{{ deviceData.device_id }}</h2>
            <span class="status-badge" :class="{ online: deviceData.device_status === 1, offline: deviceData.device_status === 0 }">
              {{ deviceData.device_status === 1 ? '在线' : '离线' }}
            </span>
          </div>
          
          <!-- 酒桶容量进度条 -->
          <div class="capacity-section">
            <div class="capacity-header">
              <span>剩余容量</span>
              <span>{{ deviceData.current_capacity }}ml / {{ deviceData.capacity }}ml</span>
            </div>
            <van-progress 
              :percentage="capacityPercentage" 
              :color="capacityPercentage > 30 ? '#67c23a' : '#f56c6c'" 
              stroke-width="10"
              radius="5"
            />
          </div>
        </div>
        
        <!-- 酒品信息 -->
        <div class="item-card">
          <img :src="deviceData.item.image" alt="酒品图片" class="item-image" />
          <div class="item-info">
            <h3>{{ deviceData.item.name }}</h3>
            <div class="price">¥{{ (deviceData.price * 500).toFixed(2) }}/斤</div>
          </div>
        </div>
        
        <!-- 店铺信息 -->
        <div class="shop-card">
          <h3>店铺信息</h3>
          <div class="shop-info">
            <div class="info-item">
              <van-icon name="shop-o" class="info-icon" />
              <span>{{ deviceData.shop.shop_name }}</span>
            </div>
            <div class="info-item">
              <van-icon name="location-o" class="info-icon" />
              <span>{{ deviceData.shop.address }}</span>
            </div>
          </div>
        </div>
        
        <!-- 打酒数量选择 -->
        <div class="quantity-section">
          <h3>选择打酒数量</h3>
          <div class="quantity-options">
            <van-button 
              size="small" 
              type="primary" 
              plain
              :class="{ active: quantity === 100 }"
              @click="selectQuantity(100)"
              :disabled="100 > deviceData.current_capacity"
            >
              100ml(二两)
            </van-button>
            <van-button 
              size="small" 
              type="primary" 
              plain
              :class="{ active: quantity === 500 }"
              @click="selectQuantity(500)"
              :disabled="500 > deviceData.current_capacity"
            >
              500ml(一斤)
            </van-button>
            <van-button 
              size="small" 
              type="primary" 
              plain
              :class="{ active: quantity === 1000 }"
              @click="selectQuantity(1000)"
              :disabled="1000 > deviceData.current_capacity"
            >
              1000ml(二斤)
            </van-button>
            <van-button 
              size="small" 
              type="primary" 
              plain
              :class="{ active: quantity === 2500 }"
              @click="selectQuantity(2500)"
              :disabled="2500 > deviceData.current_capacity"
            >
              2500ml(5斤)
            </van-button>
          </div>

        </div>
        
        
        
        <!-- 商品详情 -->
        <div class="item-description-container">
          <h3>商品详情</h3>
          <div class="item-description" v-html="deviceData.item.info"></div>
        </div>
      </div>

          <!-- 登录模态框（手机号验证码登录） -->
    <van-popup
      v-model:show="showAuthModal"
      position="bottom"
      round
      closeable
      close-icon-position="top-right"
      @close="hideAuthDialog"
      style="height: 70%"
    >
      <div class="auth-modal">
        <h3 class="auth-title">登录</h3>
        
        <!-- 登录表单 -->
        <div class="auth-form">
          <div class="form-group">
            <div class="input-wrapper">
              <van-icon name="phone" class="input-icon" />
              <input 
                type="tel" 
                placeholder="请输入手机号" 
                v-model="loginForm.phone" 
                maxlength="11" 
              />
            </div>
          </div>
          
          <div class="form-group">
            <div class="input-wrapper verification-code">
              <van-icon name="chat-o" class="input-icon" />
              <input 
                type="text" 
                placeholder="请输入验证码" 
                v-model="loginForm.verificationCode" 
                maxlength="6" 
              />
              <van-button 
                size="small" 
                type="default" 
                class="verification-btn"
                :disabled="countdown > 0 || !loginForm.phone || !/^1\d{10}$/.test(loginForm.phone)"
                @click="sendVerificationCode"
              >
                {{ countdown > 0 ? `${countdown}秒后重新发送` : '获取验证码' }}
              </van-button>
            </div>
          </div>
          
          <van-button 
            type="primary" 
            size="large" 
            class="auth-button" 
            :loading="submitting"
            :disabled="submitting"
            @click="handleLogin"
          >
            登录
          </van-button>
        </div>
      </div>
    </van-popup>


      <!-- 底部操作栏 -->
      <div class="bottom-action">
        <div class="price-display">
          <span>合计:</span>
          <span class="total-amount">¥{{ totalPrice }}</span>
        </div>
        <div style="width:20px"></div>
        <van-button 
          type="primary" 
          size="large" 
          class="order-button"
          :disabled="loading || deviceData.device_status === 0"
          @click="createOrder"
        >
          {{ deviceData.device_status === 1 ? '立即支付' : '立即支付' }}
        </van-button>
      </div>
    </div>
  </div>
    

</template>

<style scoped>
/* 登录模态框样式 */
.auth-modal {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
}

.auth-title {
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 30px;
  color: #333;
}

.verification-code {
  display: flex;
  align-items: center;
}

.verification-btn {
  margin-left: 10px;
  flex-shrink: 0;
  min-width: 120px;
}

.auth-form {
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.input-wrapper {
  display: flex;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 8px;
  padding: 0 15px;
}

.input-icon {
  color: #999;
  margin-right: 10px;
}

.input-wrapper input {
  flex: 1;
  height: 44px;
  border: none;
  background: transparent;
  font-size: 14px;
}

.auth-button {
  margin-top: 20px;
}
</style>

<script>
import { api } from '../api'
import { showToast } from 'vant'
export default {
  name: 'DeviceInfo',
  data() {
    return {
      loading: true,
      showDeviceStatus: false,
      deviceData: {
        device_id: '',
        device_status: 0,
        shop: {
          id: '',
          shop_name: '',
          address: '',
          longitude: '',
          latitude: ''
        },
        item: {
          id: '',
          name: '',
          image: '',
          info: ''
        },
        price: 0,
        current_capacity: 0,
        capacity: 0
      },
      quantity: 100,
      customQuantity: '',
      // 登录模态框相关状态
      showAuthModal: false,
      // 登录表单
      loginForm: {
        phone: '',
        verificationCode: ''
      },
      // 表单加载状态
      submitting: false,
      // 验证码倒计时
      countdown: 0,
      // 临时token（用于验证码登录）
      tempToken: ''
    }
  },
  computed: {
    // 计算剩余容量百分比
    capacityPercentage() {
      return Math.round((this.deviceData.current_capacity / this.deviceData.capacity) * 100)
    },
    
    // 计算总价
    totalPrice() {
      return (this.quantity * this.deviceData.price).toFixed(2)
    }
  },
  mounted() {
    this.getDeviceInfo()
  },
  methods: {
    // 返回上一页
    goBack() {
      this.$router.back()
    },
    
    // 显示微信支付确认弹窗
    showWxPayDialog() {
      // 使用原生confirm对话框模拟支付确认
      if (confirm(`确认支付 ¥${this.totalPrice} 吗？`)) {
        // 用户确认支付
        const payToast = showToast({
          message: '支付中...',
          type: 'loading',
          duration: 0,
          forbidClick: true
        })
        
        // 模拟支付过程
        setTimeout(() => {
          if (payToast && typeof payToast.close === 'function') {
            payToast.close()
          }
          
          // 支付成功提示
          showToast({
            message: '支付成功',
            type: 'success',
            duration: 1500
          })
          
          // 获取订单信息
          const orderInfo = JSON.parse(sessionStorage.getItem('orderInfo') || '{}')
          
          console.log('准备跳转到订单成功页面，订单信息:', orderInfo)
          
          // 确保订单信息存在且包含orderId
          if (orderInfo && orderInfo.orderId) {
            // 支付成功后跳转到订单成功页面
//            setTimeout(() => {
              console.log('跳转到订单成功页面，订单ID:', orderInfo.orderId)
              this.$router.push(`/order-success/${orderInfo.orderId}`)
//            }, 1500)
          } else {
            console.error('订单信息不完整，无法跳转')
            showToast('订单信息异常，请稍后重试')
          }
        }, 2000)
      } else {
        // 用户取消支付
        showToast('支付已取消')
      }
    },
    
    // 获取设备信息
    async getDeviceInfo() {
      const deviceId = this.$route.params.deviceId
      if (!deviceId) {
        showToast('设备编号错误')
      this.$router.push('/')
      return
      }
      
      try {
        this.loading = true
        // 调用真实API
        const res = await api.getDeviceItemInfo({ device_id: deviceId })
        this.deviceData = res.data
        this.loading = false
        
      } catch (error) {
        this.loading = false
        showToast('获取设备信息失败')
        this.$router.push('/')
      }
    },
    
    // 选择打酒数量
    selectQuantity(value) {
      if (value <= this.deviceData.current_capacity) {
        this.quantity = value
        this.customQuantity = ''
      }
    },
    
    // 处理自定义数量
    handleCustomQuantity() {
      let num = parseInt(this.customQuantity)
      if (!isNaN(num) && num >= 1 && num <= this.deviceData.current_capacity) {
        this.quantity = num
      } else if (isNaN(num)) {
        this.quantity = 100
      }
    },
    
    // 检查用户是否登录
    isUserLoggedIn() {
      return !!localStorage.getItem('token')
    },
    
    // 显示登录/注册模态框
    showAuthDialog() {
      this.showAuthModal = true
    },
    
    // 隐藏模态框
    hideAuthDialog() {
      this.showAuthModal = false
    },
    
    // 发送验证码
    async sendVerificationCode() {
      if (!this.loginForm.phone || !/^1\d{10}$/.test(this.loginForm.phone)) {
        showToast('请输入正确的手机号')
        return
      }
      
      // 开始倒计时
      this.countdown = 60
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
        }
      }, 1000)
      
      try {
        // 调用发送验证码API接口
        const res = await api.sendVerifyCode({ phone: this.loginForm.phone })
        
        // 存储临时token，后续登录时需要使用
        this.tempToken = res.data.temp_token
        
        showToast('验证码已发送')
        console.log('发送验证码到手机:', this.loginForm.phone)
      } catch (error) {
        console.error('发送验证码失败:', error)
        showToast(error.response?.data?.msg || '发送验证码失败，请稍后重试')
        // 发送失败时清除倒计时
        this.countdown = 0
      }
    },
    
    // 处理登录（验证码登录）
    async handleLogin() {
      const { phone, verificationCode } = this.loginForm
      
      // 表单验证
      if (!phone.trim()) {
        showToast('请输入手机号')
        return
      }
      
      if (!/^1\d{10}$/.test(phone)) {
        showToast('手机号格式不正确')
        return
      }
      
      if (!verificationCode.trim()) {
        showToast('请输入验证码')
        return
      }
      
      if (!/^\d{6}$/.test(verificationCode)) {
        showToast('验证码格式不正确')
        return
      }
      
      try {
        this.submitting = true
        
        // 检查是否有临时token
        if (!this.tempToken) {
          showToast('请先获取验证码')
          this.submitting = false
          return
        }
        
        // 调用短信验证码注册登录API接口
        const res = await api.smsLoginRegister({
          phone: phone,
          verify_code: verificationCode,
          temp_token: this.tempToken
        })
        
        this.submitting = false
        
        // 保存登录信息
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('user', JSON.stringify(res.data.user))
        
        showToast({ message: '登录成功', type: 'success' })
        this.hideAuthDialog()
        
        // 检查是否有重定向路径
        const redirectPath = sessionStorage.getItem('redirectPath')
        if (redirectPath && redirectPath !== '/login') {
          // 清除重定向记录
          sessionStorage.removeItem('redirectPath')
          // 跳转到之前的页面
          setTimeout(() => {
            this.$router.push(redirectPath)
          }, 500)
        }
        
      } catch (error) {
        this.submitting = false
        showToast(error.response?.data?.msg || '登录失败，请检查验证码是否正确')
      }
    },
    
    // 创建订单
    async createOrder() {
      // 检查设备状态
      if (this.deviceData.device_status === 0) {
        showToast('设备当前不可用')
        return
      }
      
      if (this.quantity > this.deviceData.current_capacity) {
        showToast('超过剩余容量')
        return
      }
      
      // 检查用户是否登录
      if (!this.isUserLoggedIn()) {
        this.showAuthDialog()
        return
      }
      
      try {
        // 在Vant v4中，直接使用showToast函数并传入options
        const toastInstance = showToast({
          message: '创建订单中...',
          type: 'loading',
          duration: 0,
          forbidClick: true
        })
        
        // 准备订单数据
        const orderData = {
          device_id: this.deviceData.device_id,
          num: this.quantity,
          price: this.deviceData.price,
          total_price: parseFloat(this.totalPrice)
        }
        // 检查token是否有效
        const tokenCheck = await api.checkToken()
        console.log('检查token结果:', tokenCheck)
        if (tokenCheck.flag !== 1) {
          showToast('登录过期，请重新登录')
          this.showAuthDialog()
          return
        }

        // 调用createOrder API接口
        const res = await api.createOrder(orderData)
        console.log('创建订单结果:', res)
        
        // 在Vant v4中，使用toast实例的close方法关闭
        if (toastInstance && typeof toastInstance.close === 'function') {
          toastInstance.close()
        }
        
        // 构造完整的订单信息
        const orderInfo = {
          ...orderData,
          totalPrice: parseFloat(this.totalPrice), // 与OrderSuccess页面使用的字段名一致
          orderId: res.data.order_id || 'ORD' + Date.now(), // 使用API返回的订单ID或生成模拟订单ID
          createTime: new Date().toISOString(),
          // 添加商品信息，供支付成功页面显示
          productInfo: {
            name: this.deviceData.item.name || '智能酒桶',
            image: this.deviceData.item.image || '',
            description: this.deviceData.item.info || ''
          }
        }
        
        // 保存订单信息到sessionStorage
        sessionStorage.setItem('orderInfo', JSON.stringify(orderInfo))
        
        // 模拟微信支付弹窗确认
        this.showWxPayDialog()
        
      } catch (error) {
        // In case of error, just show the error message
        // Don't use showToast.clear() as it's not a function in Vant v4
        console.error('创建订单失败:', error)
        showToast('创建订单失败，请稍后重试')
      }
    }
  }
}
</script>

<style scoped>
.device-info-page {
  background-color: #f8f8f8;
  min-height: 100vh;
  padding-bottom: 80px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
}

.device-info-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 10px 15px;
}

.header {
  display: flex;
  align-items: center;
  padding: 10px 0;
  margin-bottom: 15px;
  background-color: #fff;
  border-radius: 8px;
  padding: 12px 15px;
}

.back-icon {
  font-size: 18px;
  margin-right: 12px;
  color: #333;
}

.header h1 {
  font-size: 17px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.loading {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

/* 微信风格卡片 */
.device-status-card,
.item-card,
.shop-card,
.quantity-section,
.price-section {
  background-color: #fff;
  border-radius: 10px;
  padding: 16px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.status-header h2 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.status-badge {
  padding: 4px 10px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.online {
  background-color: #e8f5e9;
  color: #4caf50;
}

.status-badge.offline {
  background-color: #fce4ec;
  color: #e91e63;
}

.capacity-section {
  margin-top: 15px;
}

.capacity-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.item-image {
  width: 100%;
  height: auto;
  max-height: 200px;
  border-radius: 8px;
  object-fit: cover;
  margin-bottom: 16px;
  background-color: #f5f5f5;
}

.item-info h3 {
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.price {
  font-size: 18px;
  font-weight: 600;
  color: #e91e63;
}

.item-description-container {
  background-color: #fff;
  border-radius: 10px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.item-description-container h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.item-description {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

/* 富文本内容样式 */
.item-description :deep(p) {
  margin: 0 0 8px 0;
  line-height: 1.6;
}

.item-description :deep(img) {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 10px 0;
  border-radius: 4px;
}

.item-description :deep(strong) {
  font-weight: 600;
  color: #333;
}

.item-description :deep(em) {
  font-style: italic;
}

.item-description :deep(ul),
.item-description :deep(ol) {
  margin: 8px 0;
  padding-left: 20px;
}

.item-description :deep(li) {
  margin: 4px 0;
}

.item-description :deep(a) {
  color: #07c160;
  text-decoration: none;
}

.item-description :deep(a:hover) {
  text-decoration: underline;
}

.shop-card h3,
.quantity-section h3,
.price-section h3 {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.shop-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.info-item {
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666;
}

.info-icon {
  margin-right: 10px;
  color: #999;
  font-size: 16px;
}

/* 微信风格按钮组 */
.quantity-options {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 10px;
  margin-bottom: 16px;
}

.quantity-options .van-button {
  width: 100%;
  padding: 12px 8px;
  font-size: 14px;
  background-color: #fff;
  color: #07c160;
  border-color: #07c160;
  border-width: 1px;
  border-style: solid;
  border-radius: 8px;
  font-weight: 500;
}

.quantity-options .van-button.active {
  background-color: #07c160 !important;
  color: #fff !important;
  border-color: #07c160 !important;
}

.quantity-options .van-button:disabled {
  background-color: #f5f5f5 !important;
  color: #c9c9c9 !important;
  border-color: #e0e0e0 !important;
}

/* 微信风格输入框 */
.custom-quantity input {
  width: 100%;
  padding: 12px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  text-align: center;
  background-color: #fff;
  box-sizing: border-box;
}

.custom-quantity input:focus {
  outline: none;
  border-color: #07c160;
}

.price-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;
  color: #666;
}

.total-price {
  font-weight: 600;
  font-size: 16px;
  color: #e91e63;
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

/* 微信风格底部操作栏 */
.bottom-action {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  padding: 12px 15px;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
}

.price-display {
  flex: 1;
  display: flex;
  align-items: center;
}

.total-amount {
  font-size: 20px;
  font-weight: 600;
  color: #e91e63;
  margin-left: 5px;
}

/* 微信绿色按钮风格 */
.order-button {
  min-width: 80px;
  padding: 6px 12px;
  border-radius: 15px;
  background-color: #07c160;
  color: #fff;
  font-weight: 600;
  border: none;
  font-size: 12px;
}

.order-button:active {
  background-color: #06a852;
}
</style>